const path = require('path');
const fs = require('fs-extra');


//  每个数据包的大小
const PACKET_DATA_LENGTH = 2048;



/* 生成新的buffer */
class devicebuffe {
    constructor() {
        this.temp_ids = 0;  //包id，每个不同的包都自增1
        this.packet_ids = 0; //默认领袖包为0开始，1开始为payload包，直到本次的包发送完毕
        this.arrlist = this.sotrlist();
        this.pretreatment_data = [];
    }

    //获取文件夹列表,进行排序
    sotrlist() {
        let paths = path.resolve('./formatted_data')
        let list = fs.readdirSync(paths);
        let imglistsotr = list.sort((a, b) => {
            let reg = /.data/g;
            a = a.replace(reg, '');
            b = b.replace(reg, '');
            return a - b;
        })
        return imglistsotr
    }

    //一次处理一个文件
    pretreatment() {
        //拿到一个文件的名称
        let filename = this.arrlist.shift();
        if (filename == undefined) {
            return false;
        }

        //  要发送的类型数据
        let transfer_type_file_data = [];
        //  格式化后的文件数据
        let file_data = (fs.readJsonSync(path.join(process.cwd(), `/formatted_data/${filename}`),{throws:false})||[]).map(({id, temp_id, LE, HE}) => { return LE + HE; });

        //添加领袖包
        file_data.forEach((item) => {
            let transfer_type_row_data = [];

            //  领袖包
            let temp_id = this.temp_ids.toString(16).padStart(4, "0");
            let packet_id = "00";
            let payload_size = Number(256/8*7).toString(16).padStart(4, "0");
            let data = Number(0).toString(16).padStart(40, "0");
            let leader = Buffer.from(`bcbce0${temp_id}${packet_id}${payload_size}${data}fcfc`, 'hex');
            transfer_type_row_data.push(leader);

            //  行数据分包
            for (let i=0; i<item.length; i+=PACKET_DATA_LENGTH) {
                packet_id = (parseInt(packet_id, 16)+1).toString(16).padStart(2, "0");
                let data = item.slice(i, i+PACKET_DATA_LENGTH);
                let payload_size = (data.length/2).toString(16).padStart(4, "0");

                let packet = Buffer.from(`bcbce0${temp_id}${packet_id}${payload_size}${data}fcfc`, 'hex');
                transfer_type_row_data.push(packet);
            }

            this.temp_ids += 1;
            if (this.temp_ids > 65535) { this.temp_ids = 0; }
            transfer_type_file_data.push(transfer_type_row_data);
        })

        this.pretreatment_data.push(transfer_type_file_data);
    }
}


module.exports = devicebuffe